package cn.iocoder.yudao.module.engine.prometheus;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.engine.enums.EnumInteractionType;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Slf4j
@Component
public class EngineWebSocketMessageMetrics {
    // 预定义的SLO阈值数组
    private static final Duration[] SLO_THRESHOLDS = {
            Duration.ofMillis(100),
            Duration.ofMillis(300),
            Duration.ofMillis(500),
            Duration.ofMillis(700),
            Duration.ofMillis(1000),
            Duration.ofMillis(1500),
            Duration.ofMillis(2000),
            Duration.ofMillis(2500),
            Duration.ofMillis(3000),
            Duration.ofMillis(3500),
            Duration.ofMillis(4000),
            Duration.ofMillis(4500),
            Duration.ofMillis(5000)
    };

    @Resource
    private MeterRegistry registry;

    public void recordSuccessRequestDuration(EnumInteractionType interactionType, String path, Integer replyCount, Duration duration) {
        if (duration == null) {
            return;
        }

        if (StrUtil.isEmpty(path)) {
            path = "unknown";
        }

        final Timer timer = Timer.builder("websocket.messages.duration")
                .description("WebSocket 请求完成时间（秒）")
                .tag("protocol", "ws")  // 可选：添加标签区分协议类型
                .tag("provider", "netty")
                .tag("uri", path)
                .tag("interactionType", interactionType.getValue())
                .tag("replyCount", replyCount.toString())
                .publishPercentiles(0.5, 0.75, 0.95, 0.99)
                .publishPercentileHistogram() // 发布直方图
                .serviceLevelObjectives(SLO_THRESHOLDS)
                .register(registry);
        timer.record(duration);
    }

    public void recordSuccessRequest(EnumInteractionType interactionType, String path) {
        recordCompletedRequest(interactionType, path, "success");
    }

    public void recordCancelRequest(EnumInteractionType interactionType, String path) {
        recordCompletedRequest(interactionType, path, "cancel");
    }

    public void recordExceptionRequest(EnumInteractionType interactionType, String path) {
        recordCompletedRequest(interactionType, path, "error");
    }

    private void recordCompletedRequest(EnumInteractionType interactionType, String path, String status) {
        if (StrUtil.isEmpty(path)) {
            path = "unknown";
        }

        final Counter counter = Counter.builder("websocket.messages.complete")
                .description("WebSocket 完成的消息总数")
                .tag("protocol", "ws")  // 可选：添加标签区分协议类型
                .tag("provider", "netty")
                .tag("uri", path)
                .tag("interactionType", interactionType.getValue())
                .tag("status", status)
                .register(registry);
        counter.increment();

        final long count = (long) counter.count();
        if (count % 50 == 0) {
            log.warn("完成的消息总数: {}", count);
        }
    }

}
